import random

# 定义问题参数
L = 10  # 钢梁长度
P = 1000  # 载荷
d = 7800  # 钢梁密度

# 定义遗传算法参数
pop_size = 50  # 种群大小
max_gen = 100  # 最大迭代次数
cross_rate = 0.8  # 交叉概率
mutate_rate = 0.1  # 变异概率

# 定义染色体编码方式
def encode():
    b = random.randint(1, 10)
    h = random.randint(1, 10)
    return [b, h]

# 定义目标函数
def fitness(chromosome):
    b, h = chromosome
    w = b * h * L * d
    return P * L / w

# 定义选择操作
def select(population):
    population = sorted(population, key=lambda x: x[1], reverse=True)
    return [population[i] for i in range(int(pop_size / 2))]

# 定义交叉操作
def crossover(father, mother):
    child1 = father.copy()
    child2 = mother.copy()
    point = random.randint(0, len(father) - 1)
    child1[point:], child2[point:] = mother[point:], father[point:]
    return child1, child2

# 定义变异操作
def mutate(chromosome):
    point = random.randint(0, len(chromosome) - 1)
    chromosome[point] = random.randint(1, 10)
    return chromosome

# 初始化种群
population = [[encode(), 0] for i in range(pop_size)]

# 进行迭代
for gen in range(max_gen):
    # 计算适应度值
    for i in range(pop_size):
        population[i][1] = fitness(population[i][0])

    # 选择
    if pop_size % 2 != 0:
        pop_size -= 1  # 如果种群大小为奇数，减1确保选择操作正常进行

    parents = select(population)

    # 交叉
    for i in range(len(parents) - 1):
        if random.random() < cross_rate:
            father, mother = parents[i], parents[i + 1]
            child1, child2 = crossover(father[0], mother[0])
            population[i] = [child1, 0]
            population[i + 1] = [child2, 0]

    # 变异
    for i in range(pop_size):
        if random.random() < mutate_rate:
            population[i][0] = mutate(population[i][0])



# 输出结果
population = sorted(population, key=lambda x: x[1], reverse=True)
print("最优解为：", population[0][0])
print("最优适应度值为：", population[0][1])
